import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, constantRoutes, asyncRoutes, anyRoutes } from '@/router'
import cloneDeep from 'lodash/cloneDeep'

import router from '@/router'
const getDefaultState = () => {
  return {
    //获取用户Token
    token: getToken(),
    //用户名
    name: '',
    //用户头像
    avatar: '',
    //服务器返回的菜单信息【根据不同的角色：返回的标记信息，数组里面的元素是字符串】
    routes: [],
    //服务器返回的角色信息
    roles: [],
    //按钮权限的信息
    buttons: [],
    //对比之后【项目中已有的异步路由，与服务器返回的标记信息进行对比最终需要展示的理由】
    resultAsyncRoutes: [],
    //用户最终需要展示全部路由
    resultAllRputes: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO(state, userInfo) {
    //用户名
    state.name = userInfo.name;
    //用户头像
    state.avatar = userInfo.avatar;
    //菜单权限标记
    state.routes = userInfo.routes;
    //按钮权限标记
    state.buttons = userInfo.buttons;
    //角色
    state.roles = userInfo.roles;
  },
  SET_RESULTASYNCROUTES(state, asyncRoutes) {
    // state.resultAsyncRoutes = asyncRoutes
    console.log(asyncRoutes, 111111);
    // state.resultAllRputes = constantRoutes.concat(asyncRoutes, anyRoutes);
    state.resultAllRputes = [...constantRoutes, ...asyncRoutes, ...anyRoutes]
    router.addRoutes(state.resultAllRputes)
    console.log(state.resultAllRputes);
  }
}


// function computedAsyncRoutes(asyncRoutes, routes) {
//   let arr = []
//   for (let i = 0; i < asyncRoutes.length; i++) {
//     if (routes.indexOf(asyncRoutes[i].name) != -1) {
//       arr.push(asyncRoutes[i])
//       if (asyncRoutes[i].children && asyncRoutes[i].children.length) {
//         arr[i].children = computedAsyncRoutes(asyncRoutes[i].children, routes)
//       }
//     }
//   }
//   return arr
// }

// function computedAsyncRoutes(asyncRoutes, routes) {
//   let arr = asyncRoutes.filter((item) => {
//     if (routes.indexOf(item.name)) {

//       if (item.children && item.children.length) {
//         item.children = computedAsyncRoutes(item.children, routes)
//       }
//       return true
//     }
//   })
//   console.log(arr, '测试');
//   return arr

// }

// 定义一个函数：两个数组进行对比，对比出当前用户到底显示哪些异步路由
const computedAsyncRoutes = (asyncRoutes, routes) => {
  //过滤出当前用户【超级管理|普通员工】需要展示的异步路由
  let arr = asyncRoutes.filter(item => {
    //数组当中没有这个元素返回索引值-1，如果有这个元素返回的索引值一定不是-1 
    if (routes.indexOf(item.name) != -1) {
      //递归:别忘记还有2、3、4、5、6级路由
      if (item.children && item.children.length) {
        item.children = computedAsyncRoutes(item.children, routes);
      }
      return true;
    }
  })

  return arr
}

const actions = {
  // user login 用户登录
  async login({ commit }, userInfo) {
    const { username, password } = userInfo

    try {
      let result = await login({ username: username.trim(), password: password })
      if (result.code == 20000) {
        commit('SET_TOKEN', result.data.token);
        setToken(result.data.token)
        return 'ok'

      }
    } catch (error) {
      return Promise.reject(new Error(error.message))
    }

    // return new Promise((resolve, reject) => {
    //   login({ username: username.trim(), password: password }).then(response => {
    //     const { data } = response
    //     console.log(data, '我是登录数据');
    //     commit('SET_TOKEN', data.token)
    //     setToken(data.token)
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },




  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        console.log(data, '获取用户信息');
        //存储用户信息
        commit('SET_USERINFO', data);
        commit('SET_RESULTASYNCROUTES', computedAsyncRoutes(cloneDeep(asyncRoutes), data.routes));
        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

